package com.lj.common_web.response;

import cn.hutool.extra.spring.SpringUtil;
import com.lj.common_web.annotation.ResponseBodyEncrypt;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author luojing
 * @since 2025/5/30 11:04
 */
@RestControllerAdvice
@ConditionalOnBean(ResponseBodyEncipher.class)
@Order(99)
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ResponseBodyEncrypt annotation = getAnnotation(returnType);
        return annotation != null && annotation.value();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseBodyEncrypt annotation = getAnnotation(returnType);
        ResponseBodyEncipher encipher = SpringUtil.getBean(annotation.encipher());
        return encipher.encrypt(body, returnType, annotation);
    }

    private ResponseBodyEncrypt getAnnotation(MethodParameter returnType) {
        // 判断方法上是否有注解
        ResponseBodyEncrypt methodAnnotation = returnType.getMethodAnnotation(ResponseBodyEncrypt.class);
        if (methodAnnotation != null) {
            return methodAnnotation;
        }
        //判断类上是否有注解
        return returnType.getDeclaringClass().getAnnotation(ResponseBodyEncrypt.class);
    }
}
